<template>
  <div class="vueEditor">
    <quillEditor ref="myTextEditor" v-model="content" :options="editorOption" @change="onEditorChange($event)"></quillEditor>
  </div>
</template>

<script>
  import 'quill/dist/quill.core.css';
  import 'quill/dist/quill.snow.css';
  import 'quill/dist/quill.bubble.css';
  import { quillEditor } from 'vue-quill-editor';
  import * as qiniu from 'qiniu-js'
  import api from '@/api/apiPath'
  import Util from '../../common/utils'
  export default {
    name: "vue-editor",
    components: {quillEditor},
    data () {
      return {
        content: '',
        editorOption: {
          placeholder: 'Hello World'
        },
        token: '',
        qiniuUrl: '',
      }
    },
    props: ['value', 'disabled'],
    watch: {
      value(val) {
        this.content = val
      }
    },
    methods: {
      onEditorChange({ editor, html, text }) {
        this.$emit('input', this.content)
      },
      upload() {
        /*内存创建input file*/
        let input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/jpeg,image/png,image/jpg';
        input.onchange = e => {
          let file = e.target.files[0];
          this.uploadQiniu(file)
        };
        input.click();
      },
      // 用七牛上传
      uploadQiniu (file) {
        const fileName = file.name
        const postfix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
        const name = Util.getTimeString2(new Date().getTime())
        const token = this.token
        var putExtra = {
          fname: fileName,
          params: {},
          mimeType: null
        }
        var config = {
          useCdnDomain: true
        }
        var observable = qiniu.upload(file, name + postfix, token, putExtra, config)
        const vueThis = this
        observable.subscribe(function (res) {
          console.log('图片上传进度：', res)
        }, function (error) {
          console.error('图片上传失败：', error)
        }, function (res) {
          const imgUrl = vueThis.qiniuUrl + res.key
          let editor = vueThis.$refs.myTextEditor.quill, index = editor.getSelection().index;
          // 调用编辑器的 insertEmbed 方法，插入URL
          editor.insertEmbed(index, "image", imgUrl);
        })
      }
    },
    mounted () {
      this.$refs.myTextEditor.quill.getModule("toolbar").addHandler("image", this.upload);
      this.disabled && this.$refs.myTextEditor.quill.enable(false);
    },
    created () {
      this.axios.post(api.UPLOADTOKEN, {}).then(res => {
        this.token = res.data.data.imgToken
        this.qiniuUrl = res.data.data.qiniuUrl
      })
    }
  }
</script>

<style lang="stylus">
  .vueEditor{
    width: 80%
    .ql-container{
      min-height: 150px;
    }
  }
</style>
